import logging

import pylons.decorators

from cibynet.lib.base import *
from cibynet.model import utils as m_utils

log = logging.getLogger(__name__)


class MachinesController(AdminController):
  """REST Controller styled on the Atom Publishing Protocol"""

  def index(self, format='html', active=True):
    """GET /machines: All items in the collection."""
    c.machines_q = meta.Session.query(Machine)
    if active is not None:
      c.machines_q = c.machines_q.filter_by(active=active)
      c.cache_key = "machines_index%sactive" % (active and "_" or "_non")
    else:
      c.cache_key = "machines_index"
    return render('/machines/index.mako')

  def create(self):
    """POST /machines: Create a new item."""
    pass

  def new(self, format='html'):
    """GET /machines/new: Form to create a new item."""
    pass

  def update(self, id):
    """PUT /machines/id: Update an existing item."""
    pass

  def delete(self, id):
    """DELETE /machines/id: Delete an existing item."""
    pass

  def show(self, id, format='html'):
    """GET /machines/id: Show a specific item."""
    machines_q = meta.Session.query(Machine)
    try:
      c.machine = machines_q.filter(Machine.id == id).one()
    except:
      abort(404)
    else:
      return render('/machines/detail.mako')

  def edit(self, id, format='html'):
    """GET /machines/id;edit: Form to edit an existing item."""
    pass
    
  @pylons.decorators.jsonify
  def ping(self, id):
    """GET /machines/id;ping: Form to ping an existing machine."""
    machine = m_utils.GetOneObject(Machine, id=id)
    if machine:
      return machine.ping()
  
